﻿using QuotingTool.Domain.DataAccess;
using QuotingTool.Domain.DataAccess.Repositories;
using QuotingTool.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace QuotingTool.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class WebApiController : ApiController
    {

        #region Account
        [HttpGet]
        [Route("api/orcl/searchaccount/{name}")]
        public IEnumerable<SFAccount> SearchAccount(string name)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetAccounts(name);
        }

        [HttpGet]
        [Route("api/orcl/getaccountbyid/{id}")]
        public SFAccount GetAccountbyId(string id)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._SalesForce.getAccountByID(id);
        }

        #endregion
       
        #region Customer
        [HttpGet]
        [Route("api/orcl/getcustomers/{beginswith}")]
        public List<Customer> GetCustomers(string beginswith)
        {
            DatabaseAccess dAccess = new DatabaseAccess();


            if (beginswith == "null")
            {
                beginswith = "";
            }

            return dAccess._OracleRepo.GetCustomers(beginswith);
        }

        #endregion
       
        #region Opportunity

        [HttpGet]
        [Route("api/SF/gettopportunity/{oppid}")]
        public SFOpportunity GettOpportunity(string OppID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._SalesForce.GetOpportunity(OppID);
        }

        //string OppNumber, string OppName, string OppOwner, string SFAccount
        [HttpGet]
        [Route("api/SF/searchopportunity/{oppnumber}/{oppname}/{topdivision}/{oppowner}/{sfaccount}")]
        public List<SFOpportunity> SearchOpportunity(string OppNumber, string OppName, string TopDivision, string OppOwner, string SFAccount)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            if (OppNumber == "null")
            {
                OppNumber = string.Empty;
            }

            if (OppName == "null")
            {
                OppName = string.Empty;
            }

            if (TopDivision == "null")
            {
                TopDivision = string.Empty;
            }

            if (OppOwner == "null")
            {
                OppOwner = string.Empty;
            }

            if (SFAccount == "null")
            {
                SFAccount = string.Empty;
            }
            return dAccess._SalesForce.SearchOpp(OppNumber, OppName, TopDivision, OppOwner, SFAccount);
        }

    

        #endregion

        #region General Getters
       
        [HttpGet]
        [Route("api/orcl/getoperatingunits/")]
        public List<DBDataItem> GetOperatingUnits()
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetOperatingUnits();
        }

        [HttpGet]
        [Route("api/orcl/gettopregions/")]
        public List<DBTopRegion> GetTopRegions()
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetTopRegions();
        }

        [HttpGet]
        [Route("api/orcl/gettopdivisions/")]
        public List<TopDivision> GetTopDivisions()
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetTopDivisions();
        }

        [HttpGet]
        [Route("api/orcl/getcurrencies/")]
        public List<DBCurrency> GetCurrencies()
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetCurrnecies();
        }

        [HttpGet]
        [Route("api/orcl/getquotecustomers/{headerid}/{customertype}")]
        public List<DBDataItem> GetQuoteCustomers(string HeaderId, string CustomerType)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetQuoteCustomers(HeaderId, CustomerType);
        }

        [HttpGet]
        [Route("api/orcl/getcustomersbysoldto/{soldtopartyid}/{operatingunitid}")]
        public List<DBDataItem> GetCustomersBySoldTo(string SoldToPartyId, string OperatingUnitId)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetCustomersBySoldTo(SoldToPartyId, OperatingUnitId);
        }

        [HttpGet]
        [Route("api/orcl/getbillshipaddress/{custaccountid}/{siteusetype}/{operatingunitid}")]
        public List<DBBillShipAddress> GetBillShipAddress(string CustAccountId, string SiteUseType, string OperatingUnitId)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetBillShipAddress(CustAccountId, SiteUseType, OperatingUnitId);
        }

        [HttpGet]
        [Route("api/orcl/getmaintenanceitems/{topdivision}")]
        public List<DBDataItem> GetMaintenanceItems(string TopDivision)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetMaintenanceItems(TopDivision);
        }



        #endregion

        #region Quote Sub Line

        //// Get
        //[HttpGet]
        //[Route("api/orcl/getsublineitems/{headerid}")]
        //public List<DBSubLineItem> GetSubLineItems(string HeaderID)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.GetSubLineItems(HeaderID);
        //}        

        // update
        //[HttpPost]
        //[Route("api/orcl/updatesubline/")]
        //public DBSubLineItem UpdateSubLine([FromBody]DBSubLineItem SubLine)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.UpdateSubLine(SubLine);
        //}
        // Delete


        //[HttpDelete]
        //[Route("api/orcl/deletequotesubline/{sublineid}")]
        //public string DeleteQuoteSubLine(string SubLineID)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.DeleteQuoteSubLine(SubLineID);
        //}

      

        #endregion

        #region Quote

        // Get quote
        [HttpPost]
        [Route("api/orcl/quote/")]
        public DBQuote GetQuote([FromBody]CreateQuote SearchData)
        {

            List<DBContract> Contracts = SearchData.ContractIDs;

            string sContractIDs = string.Empty;
            string sUserName = string.Empty;

            int iContractsNum = Contracts.Count;
            int iCounter = 1;

            if (User != null && User.Identity != null)
            {
              sUserName = User.Identity.Name.Split('\\')[1];
            }

            //sUserName = "shimonabe";
            foreach (DBContract item in Contracts)
            {
                sContractIDs += item.ID;

                if (iCounter < iContractsNum)
                {
                    sContractIDs += ",";
                }
                iCounter++;
            }
            
            DatabaseAccess dAccess = new DatabaseAccess();
            DBQuote Quote;


            //QuoteNumber = "14264166,14206165,14205206,14193250,14193193,14192168,14031141,14031132,14024129,13945149,13941328,13941250,13941217,13830120,13827128,13757143,13757127,13755121,13727160,13727159,13695126,13692126,13684121,13677140,13668134,13641146,13638163,13629118,13590253,13590236,13587137,13536122,13494121,13472118,13457121,13453117,13448114,13437211,13410153,13390116,13389116,13384115,13381172,13381113,13368114,13361122,13359109,13358122,13352148,13347149,13347128,13332127,13332126,13331142,13328230,13328128,13326183,13302176,13280182,13260171,13245177,13245174,13242114,13242113,13241118,13238127,13231128,13230113,13220119,13218120,13208113,13201128,13180128,13157111,13151190,13151129,1257007,3630055,5173086,6813112,8873106,10890106,12683109,13315124,13936148,11000";
            Quote = dAccess._OracleRepo.CreateQuote(sContractIDs, sUserName, SearchData.LeadContract, null, null, null, SearchData.Currency);
            Quote = dAccess._OracleRepo.GetQuote(Quote.Header.HEADER_ID);

            return Quote;
        }


        [HttpGet]
        [Route("api/orcl/quote/{quotenumber}/{lineid}")]
        public DBQuote GetSingleQuote(string QuoteNumber, string LineID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            DBQuote Quote;
            string sIdForAuditing= string.Empty;

            string sUserName = string.Empty;

            if (LineID == "null")
            {
                Quote = dAccess._OracleRepo.GetQuote(QuoteNumber);

                if (Quote != null && !string.IsNullOrEmpty(Quote.Header.HEADER_ID))
                {
                    if (User != null && User.Identity != null)
                    {
                        sUserName = User.Identity.Name.Split('\\')[1];
                    }
                    //sUserName = "shimonabe";
                    dAccess._OracleRepo.InsertQuoteRecent(Quote.Header.HEADER_ID, "GET", sUserName);
                }
            }
            else
            {
                Quote = dAccess._OracleRepo.GetQuoteSublines(QuoteNumber, LineID);
            }

          
            return Quote;
        }


        // Create / update
        [HttpPut]
        [Route("api/orcl/quote")]
        public DBQuote UpdateQuote([FromBody]DBQuote Quote)
        {
            DBQuote quoteUpdated = null;

            DatabaseAccess dAccess = new DatabaseAccess();
            string sUserName = string.Empty;
            if (User != null && User.Identity != null)
            {
                sUserName = User.Identity.Name.Split('\\')[1];
            }
            //sUserName = "shimonabe";
            // Update
           // if (!string.IsNullOrEmpty(Quote.Header.QUOTE_NUMBER))
            //{
                quoteUpdated = dAccess._OracleRepo.UpdateQuote(Quote, sUserName);

                // for history - ENABLE AGAIN
                dAccess._OracleRepo.InsertQuoteRecent(Quote.Header.HEADER_ID, "UPDATE", sUserName);
            //}
            //// Create


            return quoteUpdated;
        }

        // Create / update
        [HttpDelete]
        [Route("api/orcl/quote/{quotenumber}/{lineid}")]
        public DBQuote DeleteQuoteAndSublines(string quotenumber, string lineid)
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            DBQuote Quote = new DBQuote();
            string sUserName = string.Empty;
            if (User != null && User.Identity != null)
            {
                sUserName = User.Identity.Name.Split('\\')[1];
            }
            //sUserName = "shimonabe";
            // Update
            if (!string.IsNullOrEmpty(quotenumber) && lineid == "null")
            {
                dAccess._OracleRepo.DeleteQuoteHeader(quotenumber);

                // for history
                dAccess._OracleRepo.InsertQuoteRecent(quotenumber, "DELETE", sUserName);
            }
            else
            {
                dAccess._OracleRepo.DeleteQuoteSubLine(quotenumber,lineid);
                Quote = dAccess._OracleRepo.GetQuote(quotenumber);

            }
            return Quote;
        }
        
        [HttpGet]
        [Route("api/orcl/setprimaryquote/{headerid}")]
        public string SetPrimaryQuote(string headerid)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.SetPrinaryQuote(headerid);
        }

        [HttpGet]
        [Route("api/orcl/quote/copyquote/{headerid}")]
        public DBQuote CopyQuote(string headerid)
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            string sUserName = string.Empty;
            if (User != null && User.Identity != null)
            {
                sUserName = User.Identity.Name.Split('\\')[1];
            }

            return dAccess._OracleRepo.CopyQuote(headerid, sUserName);
        }


        // Get Initial
        //[HttpGet]
        //[Route("api/orcl/getinitialquote/{contractids}/{currency}")]
        //public DBQuote GetInitialQuote(string ContractIDs, string currency)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.GetInitialQuoteData(ContractIDs, currency);
        //}

        //// Get
        //[HttpGet]
        //[Route("api/orcl/createquote/{contractsids}")]
        //public DBQuote CreateQuote(string ContractsIDs)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.CreateQuote(ContractsIDs);
        //}
        

     
        #endregion

        #region Quote Header


        // Insert
       /* [HttpPost]
        [Route("api/orcl/insertquoteheader/")]
        public DBQuoteHeader InsertQuoteHeader([FromBody]DBQuoteHeader QuoteHeader)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.InsertQuoteHeader(QuoteHeader);
        }
        */


        //// Update
        //[HttpPost]
        //[Route("api/orcl/updatequoteheader/")]
        //public DBQuoteHeader UpdateQuoteHeader([FromBody]DBQuoteHeader QuoteHeader)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.UpdateQuoteHeader(QuoteHeader);
        //}
        
        //// Get
        //[HttpGet]
        //[Route("api/orcl/getquoteheaders/{quotenumber}")]
        //public List<DBQuoteHeader> GetQuoteHeaders(string QuoteNumber)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.GetQuoteHeaders(QuoteNumber);
        //}

        // Delete
        //[HttpDelete]
        //[Route("api/orcl/quote/{quotenumber}/{lineid}")]
        //public string DeleteQuoteHeader(string quotenumber, string lineid)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();
        //    string sUserName = string.Empty;
        //    if (User != null && User.Identity != null)
        //    {
        //        sUserName = User.Identity.Name.Split('\\')[1];
        //    }
        //    if (!string.IsNullOrEmpty(quotenumber))
        //    {
        //        dAccess._OracleRepo.DeleteQuoteHeader(quotenumber);
        //        dAccess._OracleRepo.InsertQuoteRecent(quotenumber, "DELETE", sUserName);
        //    }
        //    else
        //    {
        //        dAccess._OracleRepo.DeleteQuoteSubLine(lineid);
        //    }
        //    return string.Empty;
        //}
        #endregion
        
        #region Quote Line


   

        // update DB
        //[HttpPost]
        //[Route("api/orcl/updateline/")]
        //public DBLineItem UpdateSubLine([FromBody]DBLineItem Line)
        //{
        //    DatabaseAccess dAccess = new DatabaseAccess();

        //    return dAccess._OracleRepo.UpdateLineItem(Line);
        //}

        // Get SF
        [HttpGet]
        [Route("api/SF/getlineitems/{accountid}")]
        public List<SFLineItem> GetLineItems(string AccountID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._SalesForce.GetLineItems(AccountID);
        }


        // Delete DB
        [HttpGet]
        [Route("api/orcl/deletequoteline/{lineid}")]
        public string DeleteQuoteLine(string LineID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.DeleteQuoteLine(LineID);
        }

        // Get DB
        [HttpGet]
        [Route("api/orcl/getlineitems/{headerid}")]
        public List<DBLineItem> GetLineItemsDB(string HeaderID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetLineItems(HeaderID);
        }

        [HttpGet]
        [Route("api/sf/createquote/{quoteheaderid}")]
        public DBProcess CreateQuote(string QuoteHeaderID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            DBProcess DBProcess = new Domain.Models.DBProcess();
            DBQuote o = dAccess._OracleRepo.GetQuoteHeaders(QuoteHeaderID);

            //return dAccess._SalesForce.CreateQuote(o);
            DBProcess.SFResults = dAccess._SalesForce.CreateQuote(o);
            DBProcess.WorkFlowResults = dAccess._OracleRepo.StartProcess(QuoteHeaderID);
            return DBProcess;
        }


    

        #endregion

        #region Quote Recent

     
        /// <summary>
        /// Get DB
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/orcl/getquoterecent/")]
        public List<DBQuoteRecent> GetQuoteRecent()
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            string sUserName = string.Empty;
            if (User != null && User.Identity != null)
            {
              sUserName = User.Identity.Name.Split('\\')[1];
            }
            //sUserName = "shimonabe";
            return dAccess._OracleRepo.GetRecentQuotes(sUserName);
        }
        
        #endregion

        #region Contracts
        [HttpGet]
        [Route("api/orcl/getcontractsbynumber/{contractnumber}")]
        public List<DBContract> GetContractsByNumber(string contractnumber)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetContractsByNumber(contractnumber);
        }

        [HttpGet]
        [Route("api/orcl/getcontractsbysonumber/{sonumber}")]
        public List<DBContract> GetContractsBySONumber(string sonumber)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetContractsBySONumber(sonumber);
        }

        [HttpGet]
        [Route("api/orcl/getcontractsbyserialnumber/{serialnumber}")]
        public List<DBContract> GetContractsBySerialNumber(string serialnumber)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetContractsBySerialNumber(serialnumber);
        }

        [HttpGet]
        [Route("api/orcl/getcontractsbyponumber/{ponumber}")]
        public List<DBContract> GetContractsByPONumber(string ponumber)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetContractsByPONumber(ponumber);
        }

        [HttpGet]
        [Route("api/orcl/getcontracts/{partyid}/{masteraccountid}/{customfilter}/{expirationperiod}/{includewarranty}/{topdivision}/{topregion}")]
        public List<DBContract> GetContracts(string partyid, string masteraccountid, string customfilter, 
                                                    string expirationperiod, string includewarranty, string topdivision, string topregion)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            if (partyid == "null")
            {
                partyid = "";
            }
            if (masteraccountid == "null")
            {
                masteraccountid = "";
            }
            if (customfilter == "null")
            {
                customfilter = "";
            }

            if (expirationperiod == "null")
            {
                expirationperiod = "";
            }

            if (includewarranty == "null")
            {
                includewarranty = "";
            }

            if (topdivision == "null")
            {
                topdivision = "";
            }

            if (topregion == "null")
            {
                topregion = "";
            }
            return dAccess._OracleRepo.GetContracts(partyid, masteraccountid, customfilter, expirationperiod, includewarranty, topdivision, topregion);
        }


        [HttpGet]
        [Route("api/orcl/generatecontract/{headerid}")]
        public string GenerateContract(string headerid)
        {
            DatabaseAccess dAccess = new DatabaseAccess();
            string sUserName = string.Empty;
            if (User != null && User.Identity != null)
            {
                sUserName = User.Identity.Name.Split('\\')[1];
            }
            //sUserName = "shimonabe";
            return dAccess._OracleRepo.GenerateContract(headerid, sUserName);
        }
        #endregion

        #region Discounts
        [HttpGet]
        [Route("api/orcl/quote/revertdiscount/{headerid}")]
        public DBQuote getRevertDiscounts(string headerid)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            string error =  dAccess._OracleRepo.RevertDiscounts(headerid);

            if (String.IsNullOrEmpty(error))
            {
                return dAccess._OracleRepo.GetQuote(headerid);
            }
            else
            {
                throw new Exception(error);
            }        
        }

        [HttpGet]
        [Route("api/orcl/quote/setdiscount/{headerid}/{OneLineDiscountType}/{OneLineDiscount}/{PrePaidIndication}/{MultiYearIncentive}")]                
        public DBQuote setDiscount(string HeaderID, string OneLineDiscountType, string OneLineDiscount, string PrePaidIndication, string MultiYearIncentive)       
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            //return dAccess._OracleRepo.RepriceQuote( HeaderID,  OneLineDiscountType,  OneLineDiscount,  PrePaidIndication,  MultiYearIncentive);
            string error = dAccess._OracleRepo.RepriceQuote(HeaderID, OneLineDiscountType, OneLineDiscount, PrePaidIndication, MultiYearIncentive);
            
            if(String.IsNullOrEmpty(error))            
            {
                return dAccess._OracleRepo.GetQuote(HeaderID);
            }
            else
            {
                throw new Exception(error);
            }            
        }

        #endregion

        #region People

        [HttpGet]
        [Route("api/orcl/findquote/{quotenumber}/{fromdate}/{todate}/{createdby}/{updatedby}/{sfdcaccountid}/{soldtoid}/{contractid}")]
        public List<DBQuote> findquote(string QuoteNumber, string FromDate, string ToDate,
                                                    string CreatedBy, string UpdatedBy, string SFDCAccountID,
                                                        string SoldToID, string ContractID)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            if (QuoteNumber == "null")
            {
                QuoteNumber = null;
            }

            if (FromDate == "null")
            {
                FromDate = null;
            }
            if (ToDate == "null")
            {
                ToDate = null;
            }

            if (CreatedBy == "null")
            {
                CreatedBy = null;
            }

            if (UpdatedBy == "null")
            {
                UpdatedBy = null;
            }

            if (SFDCAccountID == "null")
            {
                SFDCAccountID = null;
            }
            if (SoldToID == "null")
            {
                SoldToID = null;
            }

            if (ContractID == "null")
            {
                ContractID = null;
            }

            return dAccess._OracleRepo.FindQuotes( QuoteNumber,  FromDate,  ToDate,
                                                     CreatedBy,  UpdatedBy,  SFDCAccountID,
                                                         SoldToID, ContractID);
        }


          [HttpGet]
        [Route("api/orcl/getpersonname/{beginswith}")]
        public List<People> GetPersonName(string BeginsWith)
        {
            DatabaseAccess dAccess = new DatabaseAccess();

            return dAccess._OracleRepo.GetPersons(BeginsWith);
        }

        #endregion

        #region WorkFlows
          [HttpGet]
          [Route("api/orcl/startprocess/{quotenumber}")]
          public string StartProcess(string quotenumber)
          {
              DatabaseAccess dAccess = new DatabaseAccess();

              return dAccess._OracleRepo.StartProcess(quotenumber);
          }
        //start_process
        #endregion
    }
}
